//
//  MZCommunityViewController.m
//  WHISPER
//
//  Created by lanou3g on 15/12/18.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "MZCommunityViewController.h"
#import "haveImageCell.h"
#import "noImageCell.h"
#import "YPNetWorking.h"
#import "YPMakeURL.h"
#import "topModel.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "YPWebViewVC.h"

@interface MZCommunityViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UIScrollView *scroll;
@property(nonatomic,strong)UISegmentedControl *segment;
@property(nonatomic,strong)UITableView *newestTable;
@property(nonatomic,strong)UITableView *hotTable;
@property(nonatomic,strong)NSMutableArray *newsArr;
@property(nonatomic,strong)NSMutableArray *hotArr;


@end

@implementation MZCommunityViewController
static NSInteger flag1 = 0;
static NSString *str1 = @"hot";

static NSInteger flag2 = 0;
static NSString *str2 = @"addtime";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    [self.newestTable registerNib:[UINib nibWithNibName:@"haveImageCell" bundle:nil] forCellReuseIdentifier:@"haveImageCell"];
    [self.newestTable registerNib:[UINib nibWithNibName:@"noImageCell" bundle:nil] forCellReuseIdentifier:@"noImageCell"];
    [self.hotTable registerNib:[UINib nibWithNibName:@"haveImageCell" bundle:nil] forCellReuseIdentifier:@"haveImageCell"];
    [self.hotTable registerNib:[UINib nibWithNibName:@"noImageCell" bundle:nil] forCellReuseIdentifier:@"noImageCell"];
    [self addData];
    [self setRefresh];
}


-(void)setRefresh{
    self.hotTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerAction)];
    self.newestTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerAction)];
    self.hotTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footAction)];
    self.newestTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footAction)];
}

-(void)headerAction{
    if (self.segment.selectedSegmentIndex == 0) {
        //最热 解析
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str1 num:flag1] success:^(NSDictionary *dict) {
            self.hotArr = [NSMutableArray array];
            for (NSDictionary *dic in dict[@"data"][@"list"]) {
                topModel *model = [[topModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.hotArr addObject:model];
            }
            [self.hotTable reloadData];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
        }];NSLog(@"最热的刷新");
        [self.hotTable.mj_header endRefreshing];
    }else if (self.segment.selectedSegmentIndex == 1){
        //最新 解析
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str2 num:flag2] success:^(NSDictionary *dict) {
            self.newsArr = [NSMutableArray array];
            for (NSDictionary *dic in dict[@"data"][@"list"]) {
                topModel *model = [[topModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.newsArr addObject:model];
            }
            [self.newestTable reloadData];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
        }];
        [self.newestTable.mj_header endRefreshing];
        NSLog(@"下拉刷新");
    }
}

-(void)addData{
    //最热 解析
    [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str1 num:flag1] success:^(NSDictionary *dict) {
        self.hotArr = [NSMutableArray array];
        for (NSDictionary *dic in dict[@"data"][@"list"]) {
            topModel *model = [[topModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.hotArr addObject:model];
        }
        [self.hotTable reloadData];
    } fail:^(NSError *err) {
        NSLog(@"%@",err);
    }];
    //最新 解析
    [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str2 num:flag2] success:^(NSDictionary *dict) {
        self.newsArr = [NSMutableArray array];
        for (NSDictionary *dic in dict[@"data"][@"list"]) {
            topModel *model = [[topModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.newsArr addObject:model];
        }
        [self.newestTable reloadData];
    } fail:^(NSError *err) {
        NSLog(@"%@",err);
    }];
}

-(void)handleData{
    NSArray *arr = @[@"最热",@"最新"];
    self.segment = [[UISegmentedControl alloc]initWithItems:arr];
    self.segment.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
    self.segment.tintColor = [UIColor orangeColor];
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segment];
    
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, self.view.frame.size.height)];
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    self.scroll.pagingEnabled = YES;
    self.scroll.bounces = NO;
    self.scroll.delegate = self;
    [self.view addSubview:_scroll];
    
    self.newestTable = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.scroll addSubview:_newestTable];
    self.newestTable.delegate = self;
    self.newestTable.dataSource = self;
    
    self.hotTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.hotTable.dataSource = self;
    self.hotTable.delegate = self;
    [self.scroll addSubview:_hotTable];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.hotTable]) {
        return self.hotArr.count;
    }
    return self.newsArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 245;
}

//上啦加载
-(void)footAction{
    flag1 += 10;
    flag2 += 10;
    if (self.segment.selectedSegmentIndex == 0) {
        //最热 解析
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str1 num:flag1] success:^(NSDictionary *dict) {
             NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dic in dict[@"data"][@"list"]) {
                topModel *model = [[topModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [arr addObject:model];
            }
            [self.hotArr addObjectsFromArray:arr];
            [self.hotTable reloadData];
            [self.hotTable.mj_footer endRefreshing];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
            [self.hotTable.mj_footer endRefreshingWithNoMoreData];
        }];
       
    }else if (self.segment.selectedSegmentIndex == 1){
        //最新 解析
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].topicURL dict:[[YPMakeURL shareMakeURL] makeTopicDicWithStr:str2 num:flag2] success:^(NSDictionary *dict) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dic in dict[@"data"][@"list"]) {
                topModel *model = [[topModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [arr addObject:model];
            }
            [self.newsArr addObjectsFromArray:arr];
            [self.newestTable reloadData];
            [self.newestTable.mj_footer endRefreshing];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
            [self.newestTable.mj_footer endRefreshingWithNoMoreData];
        }];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.hotTable]) {
        topModel *model = self.hotArr[indexPath.row];
         if ([model.coverimg isEqualToString:@""]) {
            haveImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"haveImageCell" forIndexPath:indexPath];
            cell.title.text = model.title;
            cell.matter.text = model.content;
            cell.like.text = [NSString stringWithFormat:@"%@",model.like];
            cell.time.text = model.addtime_f;
            return cell;
        }else{
            noImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noImageCell" forIndexPath:indexPath];
            cell.title.text = model.title;
            cell.time.text = model.addtime_f;
            cell.matter.text = model.content;
            cell.like.text = [NSString stringWithFormat:@"%@",model.like];
            [cell.nameforImage sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
            return cell;
        }
      }
    if ([tableView isEqual:self.newestTable]) {
        topModel *model = self.newsArr[indexPath.row];
        if ([model.coverimg isEqualToString:@""]) {
            haveImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"haveImageCell" forIndexPath:indexPath];
            cell.title.text = model.title;
            cell.matter.text = model.content;
            cell.like.text = [NSString stringWithFormat:@"%@",model.like];
            cell.time.text = model.addtime_f;
            return cell;
        }else{
            noImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noImageCell" forIndexPath:indexPath];
            cell.title.text = model.title;
            cell.time.text = model.addtime_f;
            cell.matter.text = model.content;
            cell.like.text = [NSString stringWithFormat:@"%@",model.like];
            [cell.nameforImage sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
            return cell;
        }
    }else{
        return nil;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YPWebViewVC *commnuityWebVC = [[YPWebViewVC alloc]init];
    UINavigationController *nva = [[UINavigationController alloc]initWithRootViewController:commnuityWebVC];
    commnuityWebVC.type = @"社区";
    if (self.segment.selectedSegmentIndex == 0) {
        topModel *model = self.hotArr[indexPath.row];
        commnuityWebVC.tingID = [NSString stringWithFormat:@"http://pianke.me/webview/%@",model.contentid];
        commnuityWebVC.contendId = model.contentid;
        commnuityWebVC.shareTitle = model.title;
        commnuityWebVC.shareImage = model.coverimg;
        [self.navigationController presentViewController:nva animated:YES completion:nil];
    }else if ([tableView isEqual:self.newestTable]){
        topModel *model = self.newsArr[indexPath.row];
        commnuityWebVC.tingID = [NSString stringWithFormat:@"http://pianke.me/webview/%@",model.contentid];
        commnuityWebVC.contendId = model.contentid;
        commnuityWebVC.shareImage = model.coverimg;
        commnuityWebVC.shareTitle = model.title;
        [self.navigationController presentViewController:nva animated:YES completion:nil];
    }
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.segment.selectedSegmentIndex = self.scroll.contentOffset.x/self.scroll.frame.size.width;
}

-(void)segmentAction:(UISegmentedControl *)sender{
    switch (self.segment.selectedSegmentIndex) {
        case 0:
            self.scroll.contentOffset = CGPointMake(0, 0);
            break;
        case 1:
            self.scroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
            break;
        default:
            break;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
